import IconFont from "@/components/IconFont";
import CommonModal from "@/components/CommonModal";
import Typography from "@/pages/OrderModule/common/components/Typography";
import OrderNumberCount from '../../components/OrderNumberCount';
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import OrderStatusLabelValue from '../../components/OrderStatusLabelValue';
import { Alert, Button, Form, Modal, Popover, Radio, Space, message, Row, Col } from "antd";
import { CommonForm } from '@/pages/OrderModule/common/components/CommonForm';
import { ORDER_STATUS } from "@/pages/OrderModule/common/utils/map.js";
import OrderAreaRadioGroup from '../../components/OrderAreaRadioGroup1';
import { queryExpressList, updateLogisticsOp } from "../../../../services";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { find } from "lodash";
import { QuestionCircleOutlined } from '@ant-design/icons';
import Api from '../../service';
import { searchOrderByIds } from '../../../OrderList/services';

const renderStatusValue = (val, props = {}) => {
	return <Typography {...props}>{val}</Typography>;
}

const RenderExpressIcon = () => (
	<Popover content="只对待审核或异常订单能清空快递">
		<QuestionCircleOutlined style={{ marginLeft: '4px' }} />
	</Popover>
)

/** 批量修改快递 */
function SetExpressModal(props) {

	const { id, searchForm, selectKeys, orderList, handleCancel, handleOk } = props;

	const [form] = Form.useForm();

	const [open, setOpen] = useState(false);

	const [orderData, setOrderData] = useState([]);

	const [isOk, setIsOk] = useState(false);

	//下拉快递列表
	const [expressList, setExpressList] = useState([]);

	//针对筛选项的快递列表
	const [searchExpress, setSearchExpress] = useState([]);

	//是否请求过快递
	const [isSearch, setIsSearch] = useState(false);

	//是否是选中还是筛选状态
	const [status, setStatus] = useState();

	const [showNumber, setShowNumber] = useState({});

	const [expressConfig, setExpressConfig] = useState({});

	//当前选中的快递说明
	const [note, setNote] = useState("");

	const navigate = useNavigate();

	useEffect(() => {
		if (id) {
			const obj = find(orderList, ['id', id]) || {};
			const obj1 = obj.logisticsList[0] || {};
			form.setFieldsValue({
				expressId: Number(obj1.logisticsCompanyId)
			})
			getExpressData();
		} else {
			getExpressList(selectKeys, orderList);
		}
		setOpen(true);
	}, []);

	//初次请求下针对筛选项的快递列表
	useEffect(() => {
		if(!isSearch && status == 'search') {
			handleGetQuery();
		}
	}, [status])

	//获取筛选项的数据
	const handleGetQuery = async () => {
		START_LOADING();
		const { success, data } = await searchOrderByIds(orderData);
		END_LOADING();
		if(success) {
			setIsSearch(true);
			getExpressList(orderData, data);
		}
	}

	//获取单个快递列表
	const getExpressData = async () => {
		START_LOADING();
		const { success, data } = await Api.getOrderExpressTemplate({
			orderId: id
		})
		if (success) {
			setExpressList(data.expressTemplateVOList);
			setExpressConfig({
				warehouseName: data.warehouseName,
				warehouseStatus: data.warehouseStatus
			});
		}
		END_LOADING();
	}

	//获取快递列表
	const getExpressList = async (arr, list) => {
		START_LOADING();
		const bool = arr.some(item => {
			const obj = find(list, ['id', item]);
			return !obj.jdPlatformData?.homeDelivery;
		})
		const { success, data } = await queryExpressList({
			type: 1, // 可用快递列表 0:自发可用，1:全部可用
			isUpDoor: bool ? 0 : 1
		});
		END_LOADING();
		if (success) {
			if(status == 'search') {
				setSearchExpress([{ baseExpressId: -1, baseExpressName: '清空已有快递' }, ...data]);
			} else {
				setExpressList([{ baseExpressId: -1, baseExpressName: '清空已有快递' }, ...data]);
			}
		} else {
			expressList?.length && setExpressList([]);
		}
	};

	//选择快递
	const handleSelectExpress = e => {
		const val = e.target.value;
		const item = find(expressList, ["baseExpressId", val]);
		setNote(item?.note);
	};

	//智能快递重算
	const reCountExpress = async () => {
		const params = {
			orderIds: id ? [id] : orderData,
			strategyCodes: ["smart-logistics"]
		}
		START_LOADING();
		const { success } = await Api.appointStrategy(params);
		END_LOADING();
		if (success) {
			Modal.info({
				centered: true,
				title: "智能快递重算",
				content: '智能快递正在执行中，请稍后刷新查看！',
				onOk() {
					setIsOk(true);
					setOpen(false);
				}
			});
		}
	}

	//修改快递
	const updateLogistics = async val => {
		START_LOADING();
		const { success, data = {}, msg } = await updateLogisticsOp({
			ids: id ? [id] : orderData,
			expressId: val?.expressId
		});
		if (success) {
			if (id) {
				message.success(msg);
				setIsOk(true);
				setOpen(false);
			} else {
				Modal.info({
					centered: true,
					title: "修改快递结果",
					content: (
						<div style={{ color: "#333", marginTop: 24 }}>
							<Space size={24}>
								<span>成功数：{renderStatusValue(data.successCount, { type: "success", useBold: true })}</span>
								<span>失败数：{renderStatusValue(data.failCount, { type: "error", useBold: true })}</span>
							</Space>
						</div>
					),
					onOk() {
						setIsOk(true);
						setOpen(false);
					}
				});
			}
		}
		END_LOADING();
	};

	//点击提交
	const onOk = () => {
		form.validateFields()
			.then(val => {
				updateLogistics(val);
			})
			.catch(err => { console.log(err) });
	};

	const onCancel = () => {
		setOpen(false);
	}

	const afterClose = () => {
		if (isOk) {
			handleOk(1, orderData);
		}
		handleCancel();
	}

	const modalTitle = id ? '单个修改快递' : '批量修改快递';

	const ExpressSpan = id ? 8 : 6;

	const footer = (
		<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
			<Button type="link" onClick={() => navigate('/views/order/rule?tab1=0&tab2=4')}>
				<Typography color="#0068FF">
					<IconFont style={{ marginRight: '6px', verticalAlign: 'middle' }} type="iconsetting02" />
				</Typography>
				<Typography color="#333">获取运单号设置</Typography>
			</Button>
			<div>
				<Button onClick={onCancel}>取消</Button>
				<Button onClick={reCountExpress}>智能快递重算</Button>
				<Button onClick={onOk} type="primary">确定</Button>
			</div>
		</div>
	)

	const renderSingleExpress = () => {
		const obj = find(orderList, ['id', id]) || {};
		return (
			<Row style={{ marginBottom: '24px', color: '#333' }} gutter={80}>
				<Col>
					<OrderStatusLabelValue label="状态" value={ORDER_STATUS[obj.state]} />
				</Col>
				<Col>
					<OrderStatusLabelValue label="发货仓" value={expressConfig.warehouseStatus == 1 ? <span>{expressConfig.warehouseName}<span style={{ color: '#fd3029' }}>（已失效）</span></span> : expressConfig.warehouseName} />
				</Col>
				<Col>
					<OrderStatusLabelValue label="重量" value={obj.totalWeight + 'kg'} />
				</Col>
			</Row>
		)
	}

	//渲染批量快递
	const renderBatchExpress = () => {
		const stateArr = searchForm.stateArr ? searchForm.stateArr.filter(v => [10,20,30].includes(v)) : [10,20,30];
		const orderAreaRadioProps = {
			searchForm: { ...searchForm, stateArr },
			selectKeys,
			orderList,
			title: '',
			states: [10, 20, 30],
			updateShowNumer(obj, data) {
				setShowNumber(obj);
				setOrderData(data);
				if(status == 'search' || !status) {
					setStatus('select');
				} else {
					setStatus('search');
				}
			}
		}

		return (
			<>
				<Alert
					showIcon
					message={
						<Typography as="s1">
							<span>1、已发货、已作废的订单，以及无发货仓的订单，不允许修改快递，会直接跳过。</span> <br />
							<span>2、对<span className="common-color9">“已回传”</span>的订单，智能快递重算会略过。</span>
						</Typography>
					}
				/>
				<CommonForm
					formProps={{
						form
					}}
					columns={[
						{
							name: 'radio-group',
							slot: <OrderAreaRadioGroup wrapStyle={{ marginTop: 16 }} {...orderAreaRadioProps} />,
						},
						{
							block: (
								<OrderNumberCount
									data={[
										{ label: '待审核', value: showNumber[10] },
										{ label: '异常', value: showNumber[30], type: 'error' },
										{ label: '待发货', value: showNumber[20], type: 'warning' },
									]}
								/>
							),
						},
					]}
				></CommonForm>
			</>
		)
	}

	const finialExpress = status == 'search' ? searchExpress : expressList;

	return (
		<CommonModal
			title={modalTitle}
			open={open}
			width="672px"
			footer={footer}
			onCancel={onCancel}
			afterClose={afterClose}
		>
			{id ? renderSingleExpress() : renderBatchExpress()}
			<Form form={form}>
				< div style={{ display: 'flex', alignItems: 'center' }}>
					<SubTitle symbol as="s2" title="设置快递" wrapStyle={{ margin: "16px 0" }} />
					<div>无合适快递？<Button onClick={() => navigate('/print/config')} type="link">去新增</Button></div>
				</div>
				<Form.Item name="expressId" rules={[{ required: true, message: "请选择快递" }]}>
					<Radio.Group style={{ width: '100%' }} >
						<Row>
							{
								finialExpress.map(v => {
									return (
										<Col span={ExpressSpan}>
											<Radio onChange={handleSelectExpress} value={v.baseExpressId}>
												{v.baseExpressName}
												{v.baseExpressId == -1 ? <RenderExpressIcon /> : null}
												{(id && v.baseExpressId != -1) ? <span style={{ color: 'rgb(128 129 131)', marginLeft: '8px'}}>运费<span style={{ color: '#ff2d51'}}>￥{v.postMoney}</span></span> : null}
											</Radio>
										</Col>
									)
								})
							}
						</Row>
					</Radio.Group>
				</Form.Item>
				{note ? <Typography color="#fd3029">{APP_TITLE}代发仓快递说明：{note}</Typography> : null}
			</Form>
		</CommonModal >
	);
}

export default SetExpressModal;
